package com.example.mybatisplusdemo.common;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.mybatisplusdemo.model.domain.Flight;
import com.example.mybatisplusdemo.model.domain.ItineraryRequest;

import java.time.LocalTime;
import java.util.List;

public class FlightQueryWrapper extends QueryWrapper<Flight> {

    public FlightQueryWrapper applyTimeFilters(List<ItineraryRequest.TimeFilter> filters, boolean isDeparture) {
        if (filters == null || filters.isEmpty()) return this;

        // 使用正确的and()方法重载
        this.and(wrapper -> {
            // 使用嵌套OR条件
            for (ItineraryRequest.TimeFilter filter : filters) {
                // 获取时间范围
                LocalTime[] timeRange = getTimeRange(filter);

                // 创建时间条件
                if (isDeparture) {
                    wrapper.or(qw -> qw
                            .ge("departure_time", timeRange[0])
                            .le("departure_time", timeRange[1]));
                } else {
                    wrapper.or(qw -> qw
                            .ge("arrival_time", timeRange[0])
                            .le("arrival_time", timeRange[1]));
                }
            }

            // Consumer类型的lambda表达式不应有返回值
            // 只需构建条件而不返回任何值
        });

        return this;
    }

    private LocalTime[] getTimeRange(ItineraryRequest.TimeFilter filter) {
        if ("custom".equals(filter.getType()) && filter.getStartTime() != null && filter.getEndTime() != null) {
            return new LocalTime[]{filter.getStartTime(), filter.getEndTime()};
        }

        // 处理预定义时间范围
        return switch (filter.getType()) {
            case "morning" -> new LocalTime[]{LocalTime.of(6, 0), LocalTime.of(11, 59)};
            case "afternoon" -> new LocalTime[]{LocalTime.of(12, 0), LocalTime.of(17, 59)};
            case "evening" -> new LocalTime[]{LocalTime.of(18, 0), LocalTime.of(23, 59)};
            default -> new LocalTime[]{LocalTime.MIN, LocalTime.MAX};
        };
    }

    // 额外的过滤方法（可选）
    public FlightQueryWrapper applyAirlineFilters(List<String> airlines) {
        if (airlines != null && !airlines.isEmpty()) {
            this.in("airline_code", airlines);
        }
        return this;
    }

    public FlightQueryWrapper applyCarbonFilter(Integer maxCarbon) {
        if (maxCarbon != null) {
            this.le("carbon_emission", maxCarbon);
        }
        return this;
    }
}